package com.qf.controller.admin;

import com.qf.entity.Order;
import com.qf.entity.User;
import com.qf.service.OrderService;
import com.qf.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author wgy
 * @version V1.0
 * @project gp12_xiaomi
 * @package ${PACKAGE_NAME}
 * @description: ${TODO}
 * @date 2022/6/28 11:02
 */
@WebServlet(name = "SearchOrderServlet",urlPatterns = "/searchOrder")
public class SearchOrderServlet extends HttpServlet {
    private OrderService orderService;

    @Autowired
    public void setOrderService(OrderService orderService) {
        this.orderService = orderService;
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1判断是否登录 admin
        User admin= (User) request.getSession().getAttribute("admin");
        if(admin==null){
            response.sendRedirect(request.getContextPath()+"/admin/login.jsp");
            return;
        }
        //2接收数据
        String username = request.getParameter("username");
        String status = request.getParameter("status");
        StringBuilder where=new StringBuilder();
        List<Object> params=new ArrayList<>();
        if(!StringUtils.isEmpty(username)){
            where.append("and username like ?");
            params.add("%"+username+"%");
        }
        if(!StringUtils.isEmpty(status)){
            where.append("and status = ?");
            params.add(status);
        }
        //去掉and
        if(where.length()>0){
            where.replace(0, 3, "where");
        }

        try {
            List<Order> orderList=orderService.findByWhere(where.toString(),params);
            //4放入域中
            request.setAttribute("orderList", orderList);
            request.getRequestDispatcher("/admin/showAllOrder.jsp").forward(request, response);
        } catch (Exception e) {
            e.printStackTrace();
            response.sendRedirect(request.getContextPath()+"/admin/admin.jsp");
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}
